package com.lzy.springbootredis.controller;

import com.google.code.kaptcha.Producer;
import com.lzy.springbootredis.util.CommonUtil;
import com.lzy.springbootredis.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.nio.cs.ArrayEncoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/v1/captcha")
public class CaptchaController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private Producer captchaProducer;

    /**
     * 获取验证码图片
     * @param request
     * @param response
     */
    @GetMapping("get_captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){

        String captchaText = captchaProducer.createText();
        stringRedisTemplate.opsForValue().set(getCaptchaKey(request),captchaText,5, TimeUnit.MINUTES);

        BufferedImage image = captchaProducer.createImage(captchaText);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送验证码
     * @return
     */
    @GetMapping("seng_code")
    public JsonData sendCode(@RequestParam(value = "to",required = true) String to,
                             @RequestParam(value = "captcha",required = true) String captcha,HttpServletRequest request){
        String cacheCaptcha = stringRedisTemplate.opsForValue().get(getCaptchaKey(request));
        if (!StringUtils.isEmpty(captcha) && captcha.equalsIgnoreCase(cacheCaptcha)) {
            //删除缓存key
            stringRedisTemplate.delete(captcha);

            //todo 发送信息验证码

            return JsonData.buildSuccess();
        }else {
            return JsonData.buildError("验证码错误");
        }


    }

    /**
     * 生产key：ip+userAgent
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request){
        String ipAddr = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        return  "user-service:captcha:"+CommonUtil.MD5(ipAddr+userAgent);
    }
}
